/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.edu.kamai.client.upload;

import com.edu.kamai.config.Constant;
import java.io.File;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.util.EntityUtils;


/**
 *
 * @author xzhu
 */
public class PostFile {
    
    public PostFile(String fn,String u){
        filename = fn;
        url = u;
    }
    
    private void reFileName(){
        
    }
    
    public void uploadFile() throws Exception{
        HttpClient httpclient = new DefaultHttpClient();
        httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
        
        HttpPost httppost = new HttpPost(url);
        File file = new File(filename);
       
        //file.
        MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        mpEntity.addPart("string_field",new StringBody("i am xzhu"));
        //ContentBody cbFile = new FileBody(file, "audio/mp3");
        //mpEntity.addPart("userfile", cbFile);
        FileBody bin = new FileBody(file);
            
        mpEntity.addPart("attachment_field",bin);
        httppost.setEntity(mpEntity);
        System.out.println("executing request " + httppost.getRequestLine());
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity resEntity = response.getEntity();
        
        System.out.println(response.getStatusLine());
        if (resEntity != null) {
            System.out.println(EntityUtils.toString(resEntity));
        }
        if (resEntity != null) {
            resEntity.consumeContent();
        }
        httpclient.getConnectionManager().shutdown();
    }
    
    private String filename;
    private String url;
    
    
    public static void main(String[] arg){
        String file = "c:/我是测试的.xml";
        String url = Constant.upLoadUrl;
        PostFile p = new PostFile(file, url);
        try{
            
            p.uploadFile();
        }catch(Exception ex){
            ex.printStackTrace();
        }
    }
    
}
